<?php
/**
 * Created by PhpStorm
 * User: shen.zk
 * Date: 2023/8/26
 * Time: 17:41
 * Comment: ''
 */

namespace App\Exceptions;
use App\Common\Constant;
use App\Repository\MerchantsInfoRepo;
use App\Repository\OpenPlatformRepo;
use App\Service\Common\CheckSignService;
use Exception;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Throwable;

class BusinessException extends Exception
{
    private $errno;
    private $errmsg;
    public function __construct(array $responseCode, array $extend = [], Throwable $previous = null)
    {
        list($code, $message) = $responseCode;
        $this->errno =$code;
        $this->errmsg = $message;
        // 附加的信息
        if(!empty($extend)) {
            $field = array_keys($extend)[0];
            $this->errmsg = $extend[$field];
        } else {
            $this->errmsg = preg_replace("/%[a-z]+/", '', $this->errmsg);
        }
        parent::__construct($this->errmsg, $code, $previous);
    }

    public function render()
    {
        // 返回数据定义
        $response = [
            'error_code' => $this->errno,
            'error_msg' => $this->errmsg
        ];
        if (env('APP_ENV') == 'local')
            return response()->json($response);
        // 异常验证错误信息定义
        $err = ['error_code'=>2,"error_msg" =>"",'data'=>'','sign'=>'','encryptKey'=>'','timestamp'=>time()];

        // 获取接入模式
        $access_mode = request('access_mode');

        // 校验接入模式
        if (empty($access_mode))
        {
            $err['error_msg'] = '未定义接入模式';
            return response()->json($err);
        }

        // 接入模式参数校验 platform 平台接入  creator创作者接入
        if (!in_array($access_mode,['platform','creator']))
        {
            $err['error_msg'] = '接入模式参数错误';
            return response()->json($err);
        }

        // 获取商户号
        $access_mid = request('access_mid');

        // 获取缓存信息
        $cacheInfo = Cache::get(Constant::MERCHANTID.':'.$access_mid);
        Log::info("[异常类]获取缓存内商户信息".$cacheInfo);

        if (empty($cacheInfo))
        {
            if ($access_mode == 'platform')
            {
                $merchantsInfo = OpenPlatformRepo::getInstance()->getByPlatformNo($access_mid);
                if (empty($merchantsInfo))
                {
                    $err['error_msg'] = '平台商户不存在';
                    return response()->json($err);
                }

                if (empty($merchantsInfo->public_key))
                {
                    $err['error_msg'] = '平台商户未配置必要信息';
                    return response()->json($err);
                }
            }

            if ($access_mode == 'creator')
            {
                // 获取创作者商户信息
                $merchantsInfo = MerchantsInfoRepo::getInstance()->getByMerchantIdRepo($access_mid);
                if (empty($merchantsInfo))
                {
                    $err['error_msg'] = '创作者商户不存在';
                    return response()->json($err);
                }


                if (empty($merchantsInfo->public_key))
                {
                    $err['error_msg'] = '创作者商户未配置必要信息';
                    return response()->json($err);
                }
            }

            // 反向写入cache
            Cache::put(Constant::MERCHANTID.':'.$access_mid,json_encode($merchantsInfo));
            $cacheInfo = Cache::get(Constant::MERCHANTID.':'.$access_mid);
        }
        $cacheMerchants = json_decode($cacheInfo,true);
        $publicKey = $cacheMerchants['public_key'];

        // 获取平台自身私钥
        $privateKeyPath = config('selfpem.self_private');
        $privateKey = file_get_contents($privateKeyPath);

        // 加密加签名
        $res = CheckSignService::getInstance()->selfRequestCreateSign($response,$publicKey,$privateKey);
        $res['error_code'] = $response['error_code'];
        $res['error_msg'] = $response['error_msg'];
        return response()->json($res);
    }
}
